/*******************************************************************************
 * @note Copyright (C) 2011-2022， Shanghai Panchip Microelectronics Co., Ltd. 
 * @SPDX-License-Identifier: Apache-2.0
 * @history - V0.1, 2022-09-28
*******************************************************************************/
#include "list.h"
#include "stimer.h"

LIST(stimer_list);

uint8_t _stimer_expired(struct stimer *s)
{
    /* Note: Can not return diff >= t->interval so we add 1 to diff and return
     t->interval < diff - required to avoid an internal error in mspgcc. */
    clock_time_t diff = (clock_time() - s->start) + 1;
    return s->interval < diff;
}

void stimer_process(void)
{
    struct stimer *s;
    
    for(s = list_head(stimer_list); s != NULL; s = s->next) {
        if(_stimer_expired(s)){ //如果当前定时器已经超时
            if ( s->repeat )
            {
                s->start = clock_time();//获取当前时间
            }
            else
            {
                list_remove(stimer_list, s);    //删除当前的定时器
            }
            
            if(s->func != NULL){
                s->func(s->ptr);
            }
        }
    } 
}

void stimer_init(void)
{
    list_init(stimer_list);
}

void stimer_set(struct stimer *s, clock_time_t t, int repeat, stimer_cb_t func, void *ptr)
{
    if(s == NULL){
        return;
    }
    
    s->interval = t;
    s->repeat = repeat;
    s->func = func;
    s->ptr = ptr;
    s->start = clock_time();//获取当前时间
    list_add(stimer_list, s);
}

void stimer_stop(struct stimer *s)
{
    if(s == NULL){
        return;
    }
    
    list_remove(stimer_list, s);
}

uint8_t stimer_expired(struct stimer *s)
{
    struct stimer *t;
    
    if(s == NULL){
        return 1;
    }
    
    for(t = list_head(stimer_list); t != NULL; t = t->next) {
        if(t == s) {
            return 0;
        }
    }
    
    return 1;
} 

void stimer_restart(struct stimer *s)
{
    if(s == NULL){
        return;
    }
    
    s->start = clock_time();
    list_add(stimer_list, s);
}

